<?php

namespace App\Web\Controller;

use App\Web\Model\OperatorLog;
use App\Web\Service\RightCheck;
use EchoPHP\Http\Request;
use App\Web\Model\Role as RoleModel;


class Role extends Controller {

    public $rightCheck = [
        'index' => RightCheck::RIGHT_ACCOUNT_ROLE,
        'info' => RightCheck::RIGHT_ACCOUNT_ROLE,
        'save' => RightCheck::RIGHT_ACCOUNT_ROLE,
        'delete' => RightCheck::RIGHT_ACCOUNT_ROLE,
    ];

    /**
     * 查询角色列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function index(Request $request) {
        $pageNum = $request->getParam('pagenum/d');
        $pageLimit = $request->getParam('pagelimit/d');
        $search = [
            'rolename' => $request->getParam('rolename')
        ];

        $roleModel = new RoleModel();
        list($pageNum, $rowFrom, $rowTo) = $roleModel->paginationParameters($pageNum, $pageLimit);
        $resultBody = [];
        $count = $roleModel->getRoleListCount($search);
        $resultBody['totalCount'] = intval($count);
        $resultBody['pagenum'] = $pageNum;

        $roleList = $roleModel->getRoleList($search, '', $rowFrom, $rowTo);
        return $this->json(array_merge($resultBody, $roleList));
    }

    /**
     * 获取角色列表，用于用户管理中选择角色
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function rolelist() {
        $roleModel = new RoleModel();
        $roleList = $roleModel->getRoleList([], 'roleid,rolename,rights');
        return $this->json($roleList);
    }

    /**
     * 根据roleid查询角色详细信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     */
    public function info(Request $request) {
        $roleId = $request->getParam('roleid/d');

        $roleModel = new RoleModel();
        $roleInfo = $roleModel->getRoleInfo($roleId);
        return $this->json($roleInfo);
    }

    /**
     * 修改角色信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function save(Request $request) {
        //获取提交参数
        $roleId = $request->getPost('roleid/d', 0);
        $roleName = $request->getPost('rolename');
        $rights = $request->getPost('rights');
        $memo = $request->getPost('memo');

        //执行
        $memberModel = new RoleModel();
        $executeResult = $memberModel->saveRoleInfo($roleId, $roleName, $rights, $memo);

        return $this->json($executeResult);
    }

    /**
     * 删除角色，必须指定需要删除的角色id
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function delete(Request $request) {
        $roleId = $request->getPost('roleid/d');
        $roleModel = new RoleModel();
        $executeResult = $roleModel->deleteRole($roleId);
        return $this->json($executeResult);
    }
}
